package com.CRApp.interceptors;

import com.CRApp.pojo.Result;
import com.CRApp.utils.JwtUtil;
import com.CRApp.utils.ThreadLocalUtil;
import com.fasterxml.jackson.databind.ObjectMapper;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import java.util.Map;

/**
 * @ClassName: LoginInterceptor
 * @Author : LuoFan洛樊
 * @Date : 2025/2/6 - 12:16
 * Description : TODO
 */

@Component
public class LoginInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String url = request.getRequestURI();
        String authHeader = request.getHeader("Authorization");
        
        System.out.println("拦截到请求: " + url);
        System.out.println("Authorization头: " + authHeader);

        // 处理特殊格式的Authorization头
        String token = extractToken(authHeader);
        System.out.println("提取的token: " + token);

        // 如果是 /posts/list 接口
        if ("/posts/list".equals(url)) {
            if (token != null) {
                // 有token就解析并设置用户信息
                try {
                    Map<String, Object> claims = JwtUtil.parseToken(token);
                    ThreadLocalUtil.set(claims);
                    System.out.println("设置ThreadLocal成功: " + claims);
                } catch (Exception e) {
                    // token解析失败也允许访问，作为未登录用户
                    System.out.println("解析Token失败: " + e.getMessage());
                }
            }
            // 无论是否有token都放行
            return true;
        }

        // 其他接口的验证逻辑
        if (token == null) {
            System.out.println("Token为空，拒绝访问");
            Result error = Result.error("NOT_LOGIN");
            String json = new ObjectMapper().writeValueAsString(error);
            response.setContentType("application/json;charset=utf-8");
            response.getWriter().write(json);
            return false;
        }

        try {
            Map<String, Object> claims = JwtUtil.parseToken(token);
            ThreadLocalUtil.set(claims);
            System.out.println("验证Token成功: " + claims);
            return true;
        } catch (Exception e) {
            System.out.println("验证Token失败: " + e.getMessage());
            e.printStackTrace();
            Result error = Result.error("NOT_LOGIN_TOKEN_ERROR");
            String json = new ObjectMapper().writeValueAsString(error);
            response.setContentType("application/json;charset=utf-8");
            response.getWriter().write(json);
            return false;
        }
    }

    /**
     * 从Authorization头提取token
     * 支持多种格式:
     * 1. Bearer token格式
     * 2. 直接token格式
     * 3. Authorization:token格式
     */
    private String extractToken(String authHeader) {
        if (authHeader == null) {
            return null;
        }
        
        // 处理Bearer前缀
        if (authHeader.startsWith("Bearer ")) {
            return authHeader.substring(7);
        }
        
        // 处理Authorization:token格式
        if (authHeader.startsWith("Authorization:")) {
            return authHeader.substring("Authorization:".length());
        }
        
        // 其他情况直接返回
        return authHeader;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        //清空ThreadLocal中的数据
        ThreadLocalUtil.remove();
    }
}
 